define([
  'jquery',
  'models/AlertMessage',
  'views/View',
  'views/Modal',
  'hbs!template/users/takephoto/takephoto',
  'hbs!template/users/takephoto/takephoto-actions',
  'hbs!template/users/takephoto/success-upload',
  'takephoto'
], function($, AlertMessage, View, Modal, template, template_actions, successUploadTemplate){
  var TakePhotoView = View.extend({
    events: {
      "click button[name=shoot]":              "shoot",
      "click button[name=upload]":             "uploadPhoto"
    },
    
    template: template,

    render: function() {
      View.prototype.render.call(this);
      this.renderActions();
      return this;
    },

    renderActions: function() {
      var actionsHTML = template_actions(this.getRenderData());
      this.$("#takephoto_actions", this.el).html(actionsHTML);
    },
    
    shoot: function() {
      console.log("Shoot");
      pageLoad();
      captureToCanvas();
      this.captured = true;
      this.renderActions();
    },

    uploadPhoto: function() {
      console.log("Upload PHoto");
      var canvas = document.getElementById("canvas");
      var fd = new FormData();
      fd.append("type", "data");
      fd.append("image", canvas.toDataURL("image/png"));

      var xhr = new XMLHttpRequest();
      xhr.open("POST", "/api/me/takephoto", false);
      var that = this;
      xhr.onload = function() {
        if(xhr.status === 201) {
          var modal = new Modal({template: successUploadTemplate});
          modal.render();
        }
      };
      xhr.send(fd);
      //$.post("/api/me/takephoto", {type: "data", image: canvas.toDataURL("image/png")});
    },

    getRenderData: function() {
      var data = {};
      data._captured = this.captured;
      return data;
    }

  });

  return TakePhotoView;
});